package com.xiaoming.api;

import com.xiaoming.dao.CodeRepository;
import com.xiaoming.entity.Code;
import com.xiaoming.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@EnableFeignClients
public class CodeController {
    @Autowired
    private EmailService emailService;
    @Autowired
    private CodeRepository repository;


    @GetMapping("/create/{email}")
    @Transactional
    public boolean senEmail(@PathVariable("email") String email) throws Exception {
        String[] codes = {"0", "2", "3", "4", "5", "6", "7", "8", "9"};
        Random random = new Random();
        int i = 0;
        String content = "";
        while (i < 6) {
            int index = random.nextInt(9);
            content += codes[index];
            i++;
        }
        Code code = new Code();
        code.setCode(content);
        Long currentTimeMillis = System.currentTimeMillis();
        code.setCreatetime(new Date(currentTimeMillis));
        code.setEmail(email);
        code.setExpiretime(new Date(currentTimeMillis + 600000));
        repository.save(code);
        return emailService.sendMail(email, content);
    }

    @GetMapping("/validate/{email}/{code}")
    public int validate(@PathVariable("email") String email, @PathVariable("code") String validator) throws Exception {
        List<Code> codes = repository.findByEmailAndCodeOrderByExpiretimeDesc(email, validator);
        if (codes.size() == 0 || !validator.equals(codes.get(0).getCode())) {
            return 1;
        }
        Code code = codes.get(0);
        long current = System.currentTimeMillis();
        if (code.getExpiretime().getTime() < current) {
            return 2;
        }
        return 0;
    }
}
